﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Chat</title>    

    <link rel="shortcut icon" href="/images/favicon.ico" type="image/vnd.microsoft.icon" /> 
    <link rel="icon" href="/images/favicon.ico" type="x-icon" />
    <link rel="stylesheet" type="text/css" href="Styles/reset.css" />
    <link rel="stylesheet/less" type="text/css" href="Styles/chat.less" />

    <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
	<script src="Scripts/jquery.timers-1.2.js" type="text/javascript"></script>
	<script src="Scripts/jquery.hoverIntent.minified.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ucma.presence-1.0.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ucma.chat-1.0.js" type="text/javascript"></script>    
    <script src="Scripts/less-1.1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.functions.js" type="text/javascript"></script>
    <script src="Scripts/jquery.localisation.js" type="text/javascript"></script>
    
    <script type="text/javascript">

        var chatHeight = 477;
        var chatWidth = 456;

        //still issue on chrome
        try {
            //window.resizeBy(439 - $(window).width(), 401 - $(window).height());
            window.resizeTo(chatWidth, chatHeight);
        } catch (err) {
        }

        var webUserName;
        var employeeName;
        var topic;
        var state;
        var employeeSip;
        var session;
        var showpage;
        var topic;

        // enum holding the states
        var STATES = {
            GetWebUserName: { value: 10 },
            Chat: { value: 20 },
            Closed: { value: 30 },
            Opened: { value: 40 },
        };


        $(document).ready(function () {

        	// init localisation
        	$.localise('Lang/widget', { loadBase: true, timeout: 0 });

        	try {
        		//window.resizeBy(439 - $(window).width(), 401 - $(window).height());
        		window.resizeTo(chatWidth, chatHeight);
        	} catch (err) {
        	}

        	//get querystring parameters and put them in some vars
        	employeeName = getParameterByName("employeeName");
        	employeeSip = getParameterByName("employeeSip");
        	showpage = getParameterByName("showpage");
        	if (showpage == "") showpage = "true";
        	topic = getParameterByName("topic");

        	//generate a unique session identifier to call the service with
        	session = Math.random();

        	//write the sip to the presence widget at the top
        	$(".sip").html(employeeSip);

        	$(document).attr("title", employeeName); // only syntax that works in IE<9

        	//get employee name
        	output("employeeMessage", chatMessageResource.welcome);
        	output("statusMessage", chatMessageResource.welcomeHint);
        	changeState(STATES.GetWebUserName);

        	//focus on message input
        	$("#message").focus();

        	$("#message").keyup(function (e) {
        		if (e.keyCode == 13 && !e.shiftKey) { // Enter
        			handleMessageSendRequest();
        		}
        	});

        	//start the presence status receiving
        	$.presence({
        		'serviceUrl': 'https://lyncservice.domain.com/service.svc/',
        		'languageBaseUrl': 'http://lyncpresence.domain.com/Lang/widget',
        		'refreshRate': 5000,
        		'statusImageBaseUrl': 'http://lyncpresence.domain.com/StatusPictures/',
        		'statusImageExtension': '.jpg',
        		'onPresenceItemUpdated':
                function (settings, presenceSubscription, presenceitem) {
                	presenceStyling(settings, presenceSubscription, presenceitem, true);

                	//check if we can still chat with the user
                	var canChat = $.trim($(this).find(".canChat").html());
                	if (canChat != "true" && state != STATES.Closed) {
	                    output("infoMessage", chatMessageResource.closed.replace("[NAME]", employeeName));
                		changeState(STATES.Closed);
                		presenceitem.find(".button").addClass("highlight");
                	}
                }
        	});
        });


        function initChat() {
            $.chat({
                'serviceUrl': 'https://lyncservice.domain.com/service.svc/',
                'employeeSip': employeeSip,
                'employeeName': employeeName,
                'userName': webUserName,
                'session': session,
                'refreshRate': 1000,
                'showpage': showpage,
                'topic': topic,
                'onError':
                function (errorMessage, isFatal) {
                    if (isFatal) {
                        output("infoMessage", "Error: " + errorMessage);
                        changeState(STATES.Closed);
                    } else {
                        output("infoMessage", "Error: " + errorMessage);
                    }
                },
                'onMessageReceived':
                function (message, messageType) {
                    if (messageType == 'InstantMessage') {
                        output("employeeMessage", message);
                        setLastMessageReceived();
                    } if (messageType == 'ComposingStateChanged') {
                        var composingState = message;
                        if (composingState == "Idle") {
                            var currentLastMessageReceived = $("#lastMessageReceived").data("currentLastMessageReceived");
                            if (currentLastMessageReceived != undefined) {
                                $("#lastMessageReceived").html(currentLastMessageReceived);
                            } else {
                                $("#lastMessageReceived").html("");
                            }
                            $("#lastMessageReceived").removeClass("isTyping");
                        } else if (composingState == "Composing") {
                            output("statusMessage", chatMessageResource.composingMessage.replace("[NAME]", employeeName));
                            $("#lastMessageReceived").addClass("isTyping");
                        }
                    } else if (messageType == 'ServiceNotification') {
                        output("statusMessage", chatMessageResource.waitingForFirstResponseHint);
                    } else if (messageType == 'ChatRequestAccepted') {
                        changeState(STATES.Chat);
                        output("statusMessage", "Chat established.");
                    } else if (messageType == 'ChatRequestDenied') {
                        output("infoMessage", chatMessageResource.denied);
                        changeState(STATES.Closed);
                    } else if (messageType == 'ServiceError') {
                        output("infoMessage", message);
                        changeState(STATES.Closed);
                    } else if (messageType == 'ChatClosed') {
                        output("infoMessage", chatMessageResource.closed.replace("[NAME]", employeeName));
                        changeState(STATES.Closed);
                    }
                }
            });
        }



        function handleMessageSendRequest() {
            var message = readInput();
            if (message != '') {

                if (state == STATES.GetWebUserName) {
                    webUserName = message;
                    output("webUserMessage", message);
                    $(document).oneTime(1000, function () { // 1 second delay to catch the user's attention
                        output("employeeMessage", chatMessageResource.invitation.replace("[NAME]", webUserName));
                    });
                    changeState(STATES.Opened);
                    initChat();

                } else if (state == STATES.Chat) {
                    output("webUserMessage", message);
                    sendToServer(message, webUserName);
                }
            }
            clearInput();
            $("#message").focus();
        }

        function sendToServer(message, prefix) {
            if (!(prefix === undefined)) {
                message = prefix + ": " + message;
            }
            $.chat('sendToServer', message);
        }

        function changeState(newState) {
            if (newState == STATES.Opened) {
                output("statusMessage", chatMessageResource.openingHint);
                $("#message").attr("disabled", "disabled");
            } else if (newState == STATES.Chat) {
                $("#message").removeAttr("disabled");
            } else if (newState == STATES.Closed) {
                $("#message").attr("disabled", "disabled");
                output("statusMessage", "");
                $.chat('dispose');
            }

            state = newState;
        }

        function clearInput() {
            $("#message").val("");
        }

        function readInput() {
            var input = $.trim($("#message").val());
            return input;
        }

        // writes a message to the conversation window. Chooses layout/template by type.
        function output(type, message) {

            //convert links to a href's
            message = message.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g, '<a href="$1" target="_blank">$1</a>');

            var previousOutput = $("#conversation > :last-child");

            if (type == "employeeMessage") {
                if (previousOutput.is(".fromEmployee")) {
                    //append to previous output container
                    previousOutput.append("<div class='content'>" + message + "</div>");
                } else {
                    //create new messageContainer
                    var templateData = [{ sender: employeeName, message: message, time: getTimeString()}];
                    $("#employeeMessageTemplate").tmpl(templateData).appendTo("#conversation");
                }

            } else if (type == "webUserMessage") {
                if (previousOutput.is(".fromWebUser")) {
                    //append to previous output container
                    previousOutput.append("<div class='content'>" + message + "</div>");
                } else {
                    //create new messageContainer
                    var templateData = [{ sender: webUserName, message: message, time: getTimeString()}];
                    $("#webUserMessageTemplate").tmpl(templateData).appendTo("#conversation");
                }

            } else if (type == "infoMessage") {
                var templateData = [{ message: message}];
                $("#infoMessageTemplate").tmpl(templateData).appendTo("#conversation");

            } else if (type == "statusMessage") {
                $("#lastMessageReceived").html(message);
            }

            $("#conversation").scrollTop(99999);
        }

        function setLastMessageReceived() {
            $("#lastMessageReceived").html("Last message received on " + getDateString() + " at " + getTimeString() + ".");

            //store this string so that we can show it again when the lync user stops typing.
            $("#lastMessageReceived").data("currentLastMessageReceived", $("#lastMessageReceived").html());
        }

        function getTimeString() {
            var currentDate = new Date();
            var hours = currentDate.getHours();
            var minutes = currentDate.getMinutes();
            if (minutes < 10) minutes = "0" + minutes;
            return currentDate.getHours() + ":" + currentDate.getMinutes();
        }

        function getDateString() {
            var currentDate = new Date();
            var day = currentDate.getDate();
            var month = currentDate.getMonth();
            var year = currentDate.getFullYear();
            return day + "/" + month + "/" + year;
        }

        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        }

        $(window).bind("beforeunload", function () {
        	sendToServer("The web user closed the chat window.");
        });
    </script>
</head>
<body>
    <div id="chatWindow">
        <div id="chatWindowHeader">
            <div class="presenceitem">
                <div class="availability">
                </div>
                <img class="statusImage" style="display: none;" />
                <div class="sidePanel">
                    <div class="name">
                    </div>
                    <div class="status">
                    </div>
                    <div class="jobtitle">
                    </div>
                </div>
                <div class="buttons">
                    <div class="button emailbutton left enabled">
                        <img class="emailIcon" src="images/email.png" />E-mail</div>
                    <div class="button phonebutton right enabled">
                        <img class="phoneIcon" src="images/phone.png" />Phone</div>
                    <div class="phonetooltip right hidden">
                        <div class="phoneContainer">   
                            <img src="images/phone.png" />
                            <div>
                                <div class="phonedescription">Work</div>
                                <div class="phone"></div>
                            </div>
                        </div>
                        <div class="phoneContainer">   
                            <img src="images/mobile.png" />
                            <div>
                                <div class="phonedescription">Mobile</div>
                                <div class="mobile"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sip hidden">
                </div>
                <div class="canChat hidden">
                </div>
                <div class="email hidden">
                </div>
            </div>
        </div>
        <div id="chatWindowBody">
            <div id="conversation">
            </div>
            <div id="lastMessageReceived">
            </div>
            <div id="typeMessageContainer">
                <textarea id="message" style="resize: none;"></textarea><input type="button" id="btnSendMessage" value="Send" />
            </div>
        </div>
    </div>
    <!-- webUserMessageTemplate -->
    <script id="webUserMessageTemplate" type="text/html">
        <div class="messageContainer fromWebUser">
            <div class="sender">
                {{= sender}}</div>
            <div class="time">
                {{= time}}</div>
            <div class="content">{{html message}}</div>
        </div>
    </script>
    <!-- employeeMessageTemplate -->
    <script id="employeeMessageTemplate" type="text/html">
        <div class="messageContainer fromEmployee">
            <div class="sender">
                {{= sender}}</div>
            <div class="time">
                {{= time}}</div>
            <div class="content">{{html message}}</div>
        </div>
    </script>
    <!-- infoMessageTemplate -->
    <script id="infoMessageTemplate" type="text/html">
        <div class="infoContainer">
            <div class="content">
                {{= message}}
            </div>
        </div>
    </script>
</body>
</html>
